﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace RATSharpW7.Converters
{
    public class DateConverter : FrameworkElement, IValueConverter
    {

        /// <summary>
        /// the whole concept of converters in XAML is just weird..it is not possible to bind any kind of dynamic parameter into converters. 
        /// So this is a small workaroud - I´ve added a new property to converter and now you can use something like 
        /// "<converters:DateConverter x:Key="dateConv"   DateTime="{Binding SelectedDate}" />" which is much more usable than 
        /// system of not-bindable parameters and so on...
        /// </summary>
        public DateTime DateTime
        {
            get { return (DateTime)GetValue(DateTimeProperty); }
            set { SetValue(DateTimeProperty, value); }
        }

        public static readonly DependencyProperty DateTimeProperty =
           DependencyProperty.Register("DateTime", typeof(DateTime), typeof(DateConverter),
           new PropertyMetadata(DateTime.Now, new PropertyChangedCallback(OnDateTimeChanged)));

        private static void OnDateTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((DateConverter)d).OnDateTimeChanged(e);
        }

        protected virtual void OnDateTimeChanged(DependencyPropertyChangedEventArgs e)
        {
        }


        /// <summary>
        /// Format text to localized datetime format. 
        /// If dateTeime is equals to today's date, trimm the date
        /// part and keep only the time printed
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            if (value == null) return "";

            DateTime val = value is DateTime ? (DateTime)value : DateTime.Now;
           
            if (val.Date.Equals(DateTime.Date))
            {
              return  String.Format("{0:HH:mm}", val);

            }
            else
            {
                return String.Format("{0:dd.MM. HH:mm}", val);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
